﻿import re

import logging
from datetime import datetime

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api.urlfetch import fetch
from google.appengine.api import mail

from views_common import *
import models

import smth_iphone as smth


# ##########################################################################################################################
# /
def index(request):
    user = getUser()
    logging.info(user.email())
    config = db.GqlQuery("SELECT * FROM Configuration WHERE user=:1", user).get()
    if config is None:
        config = models.Configuration(user=user,showTitle=True,showHead=True,showPost=True,showRef=True,showSignature=True,showAttachment=True,showThreadNewPage=True,showThreadOriginUrl=True,threads_count=0,boards_count=0,posts_count=0)
        config.put()
        logging.info('new config added')
    
    login_text, login_url = getLoginAndUrl(request)
    
    is_logged_in = False
    if users.get_current_user():
        is_logged_in = True
        
    payload = {'is_logged_in': is_logged_in ,'login_text':login_text, 'login_url':login_url, }
    
    return render('iphone/base.html', payload)

# ##########################################################################################################################
# /top10/
def top10(request):
    top10_threads = smth.getTop10ArticlesList()
    payload = {'title': '十大热门话题', 'threads': top10_threads, }
    return render('iphone/threads.html', payload)

# ##########################################################################################################################
# /
def boards(request):
    payload = None
    return render('iphone/boards.html', payload)
    
# ##########################################################################################################################
# /posts/
def posts(board_name, page_num):
    posts, page_num_new = smth.getPostList(board_name, page_num)
        
    pre_page_num = None
    next_page_num = None
    
    if page_num != None:
        next_page_num = int(page_num_new)+1
        
    if page_num_new>1:
        pre_page_num = int(page_num_new)-1
        
    payload = {'board_name': board_name, 'posts': posts, 'page_num': page_num_new, 'pre_page_num': pre_page_num, 'next_page_num': next_page_num,  }
    return render('iphone/posts.html', payload)
    
# ##########################################################################################################################
# /b/board_name
def board(request, board_name):
    #board_name = request.GET.get("bn", None)
    page_num = request.GET.get("pn", None)
    return posts(board_name, page_num)

# ##########################################################################################################################
# /bn/
def bn(request):
    board_name = request.POST.get("bn", "NewExpress").strip()
    page_num = request.GET.get("pn", None)
    return posts(board_name, page_num)
    
# ##########################################################################################################################
# /tposts/
def tposts(request):
    board_name = request.GET.get("bn", None)
    thread_id = request.GET.get("tid", None)
    page_num = request.GET.get("pn", None)
    half = request.GET.get("h", 1)

    thread_title, posts, page_num, page_count = smth.getThreadPostList(board_name, thread_id, page_num)
    
    if thread_title and thread_title.startswith('同主题阅读：'):
        thread_title = thread_title[thread_title.find('：')+3:]
    
    pre_page_num = None
    next_page_num = None
    if page_num<page_count:
        next_page_num = int(page_num)+1
    if page_num>1:
        pre_page_num = int(page_num)-1
    
    if half ==1:
        half_posts = posts[0:10]
    else:
        half_posts = posts[10:]
        
    page_order_str =''
    idx = len(posts)
    for post in posts:
        post.word_count = "%02d." % ((int(page_num)-1)*20+idx)
        page_order_str = str(post.post_id)+','+page_order_str
        idx -= 1
    
    page_num = int(page_num)
    page_count = int(page_count)
        
    payload = {'title': thread_title, 'posts': reversed(posts), 'board_name': board_name, 'thread_id': thread_id, 'page_num': page_num, 'next_page_num': next_page_num, 'pre_page_num': pre_page_num, 'page_order_str': page_order_str, }
    return render('iphone/tposts.html', payload)

# ##########################################################################################################################
# /post/
def post(request):
    logging.info('ok')
    html = '<div id="posthtml" class="postcontent">'+postHTML(request)+'</div>'
    logging.info(html)
    return HttpResponse(html)
    
def tpost(request):
    board_id = request.GET.get("bid", None)
    post_id = request.GET.get("pid", None)

    page_order_str = request.GET.get("pids", None)
    logging.info("page_order_str:"+page_order_str)
    logging.info("post_id:"+post_id)
    next_post_id = page_order_str[page_order_str.find(post_id+',')+len(post_id+','):]
    logging.info("next_post_id:"+next_post_id)
    next_post_id = next_post_id[:next_post_id.find(',')]
    logging.info("next_post_id:"+next_post_id)
    if next_post_id=='':
        next_post_id = None
        
    page_order_str = request.GET.get("pids", None)
    logging.info("page_order_str:"+page_order_str)
    logging.info("post_id:"+post_id)
    idx = page_order_str.find(post_id+',')
    if idx==0:
        pre_post_id = None
    else:
        pre_post_id = page_order_str[:idx-1]
        logging.info("pre_post_id:"+pre_post_id)
        pre_post_id = pre_post_id[pre_post_id.rfind(',')+1:]
        logging.info("pre_post_id:"+pre_post_id)
    
    payload = {'content': postHTML(request), 'board_id': board_id, 'pre_post_id': pre_post_id, 'next_post_id': next_post_id, 'page_order_str': page_order_str, }
    return render('iphone/tpost.html', payload)
    
# ##########################################################################################################################
def postHTML(request):
    board_id = request.GET.get("bid", None)
    post_id = request.GET.get("pid", None)

    post = db.GqlQuery("SELECT * FROM Post WHERE board_id=:1 and post_id=:2", int(board_id), int(post_id)).get()
    if post is None:
        post_id, post_title, head, content_text, ref, attachment_html, signature = smth.getPostContent(board_id, post_id)
        
        post = models.Post(title=utf8Str(post_title), board_id=int(board_id), post_id=int(post_id), head=utf8Str(head), ref=utf8Str(ref), attachment=utf8Str(attachment_html), signature=utf8Str(signature), content=utf8Str(content_text))
        try:
            post.put()
        except apiproxy_errors.OverQuotaError, message:
            logging.error(message)
            models.cleanOldPosts()
            mail.send_mail(sender="ipsmth@googleappengine.com",
              to="Demiao Lin <ldmiao@gmail.com>",
              subject="It seems that ipsmth had a OverQuotaError",
              body='''Dear Demiao:

                        Your http://ipsmth.appspot.com just had a OverQuotaError:
                        --------------------------------
                        '''
                        + message +
                        '''
                        --------------------------------

                        Please check it if you have time.

                        From: ipsmth@googleappengine.com
                        ''')

    config = db.GqlQuery("SELECT * FROM Configuration WHERE user=:1", getUser()).get()
    
    logging.info(post.toHTML(config))
    
    return post.toHTML(config)
    
def utf8Str(str):
    if not str:
        str = ""
    return unicode(str, 'utf-8', 'ignore')
    
# ##########################################################################################################################
# /settings/
def settings(request):
    user = getUser()
    logging.info(user.email())
    config = db.GqlQuery("SELECT * FROM Configuration WHERE user=:1", user).get()
    if config is None:
        config = models.Configuration(user=user,showTitle=True,showHead=True,showPost=True,showRef=True,showSignature=True,showAttachment=True,showThreadNewPage=True,showThreadOriginUrl=True,threads_count=0,boards_count=0,posts_count=0)
        config.put()
        
    payload = { 'config': config,  }
    return render('iphone/settings.html', payload)

# ##########################################################################################################################
# /c/
def config(request):
    showTitle = request.POST.get("showTitle", "False")
    showHead = request.POST.get("showHead", "False")
    showPost = request.POST.get("showPost", "False")
    showRef = request.POST.get("showRef", "False")
    showAttachment = request.POST.get("showAttachment", "False")
    showSignature = request.POST.get("showSignature", "False")
    
    showThreadNewPage = request.POST.get("showThreadNewPage", "False")
    showThreadOriginUrl = request.POST.get("showThreadOriginUrl", "False")
    
    if showTitle == 'True':
        showTitle = True
    else:
        showTitle = False
        
    if showHead == 'True':
        showHead = True
    else:
        showHead = False
        
    if showPost == 'True':
        showPost = True
    else:
        showPost = False
        
    if showRef == 'True':
        showRef = True
    else:
        showRef = False
        
    if showSignature == 'True':
        showSignature = True
    else:
        showSignature = False
    
    if showAttachment == 'True':
        showAttachment = True
    else:
        showAttachment = False
    
    if showThreadNewPage == 'True':
        showThreadNewPage = True
    else:
        showThreadNewPage = False
        
    if showThreadOriginUrl == 'True':
        showThreadOriginUrl = True
    else:
        showThreadOriginUrl = False
    
    
    user = getUser()
    config = db.GqlQuery("SELECT * FROM Configuration WHERE user=:1", user).get()
    if config:
        config.showTitle = showTitle
        config.showHead = showHead
        config.showPost = showPost
        #logging.info('showPost:'+str(showPost))
        config.showRef = showRef
        config.showSignature = showSignature
        config.showAttachment = showAttachment
        config.showThreadNewPage = showThreadNewPage
        config.showThreadOriginUrl = showThreadOriginUrl
        config.put()
    
    return settings(request)
